package h0908;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @author 不知名帅哥
 * @version 1.0
 * @description 分割回文串
 * @date 2024/9/8 17:12
 */
public class CutPalindromeString {
    public static void main(String[] args) {
        String s="aab";
        CutPalindromeString cutPalindromeString=new CutPalindromeString();
        List<List<String>> res = cutPalindromeString.partition(s);
        System.out.println(res);
    }

    public List<List<String>> partition(String s) {
        List<List<String>> res = new ArrayList<>();
        LinkedList<String> list = new LinkedList<>();
        backTrack(res, list, s, 0, s.length());
        return res;
    }

    private void backTrack(List<List<String>> res, LinkedList<String> list, String s, int start, int n) {
        if (start == n) {
            res.add(new LinkedList<>(list));
            return;
        }
        for (int i = start; i < n; i++) {
//            String substring = s.substring(start,i+1);
            if (isPalindrome(s,start,i+1)){
                list.addLast(s.substring(start,i+1));
                backTrack(res, list, s, i+1, n);
                list.removeLast();
            }
        }
    }

    private boolean isPalindrome(String s) {
        int left = 0;
        int right = s.length() - 1;
        while (left <= right) {
            if (s.charAt(left) != s.charAt(right)) {
                return false;
            }
            left++;
            right--;
        }
        return true;
    }
    private boolean isPalindrome(String s,int start,int end) {
        end--;
        while (start <= end) {
            if (s.charAt(start) != s.charAt(end)) {
                return false;
            }
            start++;
            end--;
        }
        return true;
    }

}
